package com.bingxue.edu.management.shop.activity;

import cn.hutool.core.util.StrUtil;
import com.bingxue.edu.common.enums.ClassCategoryEnum;
import com.bingxue.edu.common.enums.CommonStatusEnum;
import com.bingxue.edu.common.enums.ReceiveTypeEnum;
import com.bingxue.edu.management.education.model.entity.Enrollment;
import com.bingxue.edu.management.education.model.entity.Parent;
import com.bingxue.edu.management.education.model.entity.Student;
import com.bingxue.edu.management.education.service.EnrollmentService;
import com.bingxue.edu.management.education.service.ParentService;
import com.bingxue.edu.management.education.service.StudentService;
import com.bingxue.edu.management.shop.model.entity.Activity;
import com.bingxue.edu.management.shop.model.entity.OrderItem;
import com.bingxue.edu.management.shop.model.req.CouponDistributeReq;
import com.bingxue.edu.management.shop.service.ActivityService;
import com.bingxue.edu.management.shop.service.CouponService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import static com.bingxue.edu.management.education.model.entity.table.ClassInfoTableDef.CLASS_INFO;
import static com.bingxue.edu.management.education.model.entity.table.EnrollmentTableDef.ENROLLMENT;
import static com.bingxue.edu.management.education.model.entity.table.StudentTableDef.STUDENT;

/**
 * 老带新活动 服务类
 * @author panbo
 * @since 2024/11/12
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LdxActivityService {

    private final ParentService parentService;
    private final StudentService studentService;
    private final EnrollmentService enrollmentService;
    private final CouponService couponService;
    private final ActivityService activityService;

    public void process(Enrollment enrollment, OrderItem orderItem) {
        // 1. 判断活动是否开启
        Activity activity = activityService.getByCode(ActivityConstants.LDX_CODE);
        if (activity.getStatus() != CommonStatusEnum.ENABLED) {
            log.debug("老带新活动未开启，跳过老用户优惠券发放");
            return;
        }
        // 2. 判断是否满足条件
        // 是否设置了推荐人
        Student student = studentService.getById(enrollment.getStudentId());
        Parent parent = parentService.getById(student.getParentId());
        String recommenderPhone = parent.getRecommender();
        if (StrUtil.isEmpty(recommenderPhone)) {
            log.info("手机号[{}]未设置推荐人，跳过老用户优惠券发放", parent.getMobilePhone());
            return;
        }
        if (recommenderPhone.equals(parent.getMobilePhone())) {
            log.info("手机号[{}]推荐人为自己，跳过老用户优惠券发放", parent.getMobilePhone());
            return;
        }
        // 是否为新用户
        if (!isNewUser(parent.getMobilePhone(), enrollment)) {
//        if (!isNewUser(parent.getMobilePhone(), orderItem)) {
            log.info("手机号[{}]不是新用户，跳过老用户优惠券发放", parent.getMobilePhone());
            return;
        }
        // 推荐人是否存在
        Parent recommender = parentService.getByPhone(recommenderPhone);
        if (recommender == null) {
            log.warn("推荐人手机号[{}]不存在，跳过老用户优惠券发放", recommenderPhone);
            return;
        }
        // 3. 获取活动配置
        LdxActivityConfig config = ActivityUtil.getActivityConfig(activity, LdxActivityConfig.class);
        if (StrUtil.isEmpty(config.getOldUserCouponTemplateId())) {
            log.warn("老带新活动配置-老用户赠送优惠券id[{}]不存在，跳过老用户优惠券发放", config.getOldUserCouponTemplateId());
            return;
        }
        // 4. 老用户发放优惠券
        CouponDistributeReq couponDistributeReq = new CouponDistributeReq();
        couponDistributeReq.setParentId(recommender.getId());
        couponDistributeReq.setCouponTemplateId(config.getOldUserCouponTemplateId());
        couponDistributeReq.setReceiveType(ReceiveTypeEnum.BACKEND);

        for (int i = 0; i < config.getOldUserCouponCount(); i++) {
            couponService.distributeCoupon(couponDistributeReq);
        }

        log.info("老带新活动-老用户优惠券发放成功，报名id: {}, 新用户: {}, 老用户: {}, 发放数量: {}",
                enrollment.getId(),
                parent.getMobilePhone(),
                recommender.getMobilePhone(),
                config.getOldUserCouponCount()
        );
    }

    /**
     * 根据手机号判断家长是否为新用户
     * 判断依据：家长不存在长期班的报名记录
     * @param parentMobile 家长手机
     * @param currentEnrollment 当前报名记录
     * @return 是否为新用户
     */
    private boolean isNewUser(String parentMobile, Enrollment currentEnrollment) {
        return !enrollmentService.queryChain()
                .leftJoin(STUDENT).on(STUDENT.ID.eq(ENROLLMENT.STUDENT_ID))
                .leftJoin(CLASS_INFO).on(CLASS_INFO.ID.eq(ENROLLMENT.CLASS_ID))
                .where(ENROLLMENT.CREATE_TIME.lt(currentEnrollment.getCreateTime()))
                .where(ENROLLMENT.ID.ne(currentEnrollment.getId()))
                .and(STUDENT.PARENT_PHONE.eq(parentMobile))
                .and(CLASS_INFO.CLASS_CATEGORY.eq(ClassCategoryEnum.LONG_TERM_CLASS))
                .exists();
    }

//    @Async
//    @TransactionalEventListener(fallbackExecution = true)
//    public void onEnrollPassed(EnrollPassedEvent event) {
//        activityService
//        EnrollRecord enrollRecord = event.getEnrollRecord();
//        ldx(enrollRecord);
//    }
}
